//
//  JPChoosePhotosView.m
//  JPChoosePhotosViewDemo
//
//  Created by Carpenter on 2018/2/12.
//  Copyright © 2018年 carpenter. All rights reserved.
//

#import "JPChoosePhotosView.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>

@interface JPChoosePhotosView()

/**
 选取的图片地址集合
 */
@property (nonatomic ,strong) NSMutableArray * chooseAssetsArrayM;

/**
 选取的图片
 */
@property (nonatomic ,strong) NSMutableArray * choosePhotosArrayM;

/**
 定制内容
 */
@property (nonatomic ,strong ,readwrite) JPPhotosConfigure * configure;

/**
 存放点击按钮
 */
@property (nonatomic ,strong) NSMutableArray<JPPhotoView *> * buttonsArrayM;

/**
 展示视图
 */
@property (nonatomic ,strong) UIView * contentView;

@end

static NSString * const ReuseIdentifier = @"cellReuseIdentifier";

@implementation JPChoosePhotosView

@synthesize choosePhotosArrayM = _choosePhotosArrayM;

-(void)setChoosePhotosArrayM:(NSMutableArray *)choosePhotosArrayM{
   
    _choosePhotosArrayM = choosePhotosArrayM;
    
    [self reloadData];

}

//MARK: - LifeCycle

+(instancetype)jp_sheardChoosePhotosViewWithPhotosConfigure:(JPPhotosConfigure *)configure{
 
    JPChoosePhotosView * view = [[self alloc] initWithFrame:CGRectMake(0, 0, configure.viewWidth, 0)];
    
    view.configure = configure;
    
    [view createSubviews];
    
//    view.isAllowPresentPIC = true;
    view.jp_willPresentImagePickerControllerBlock = ^BOOL{
        return true;
    };
 
    return view;
}



-(void)createSubviews{
    
    self.buttonsArrayM = [NSMutableArray array];
    
    self.contentView = [UIView new];
    [self addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    //循环创建按钮（根据最大数量来创建）
    for (NSInteger index = 0; index < self.configure.maxNum; index ++) {
        
        JPPhotoView * view = [[JPPhotoView alloc] initWithFrame:CGRectMake(0, 0, self.configure.itemSize.width, self.configure.itemSize.height)];
        view.tag = index;
        [view.photoBtn addTarget:self action:@selector(choosedPhotosClick:) forControlEvents:UIControlEventTouchUpInside];
        [view.deleteBtn addTarget:self action:@selector(deleteCurrentImageClick:) forControlEvents:UIControlEventTouchUpInside];
        [view.deleteBtn setImage:self.configure.deleteImage forState:UIControlStateNormal];
        [view.photoBtn setBackgroundImage:self.configure.addphotoImage forState:UIControlStateNormal];
        [self.contentView addSubview:view];
        [self.buttonsArrayM addObject:view];
        
        view.hidden = true;
        
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.configure.horizontalClearance + (self.configure.itemSize.width + self.configure.horizontalClearance)*(index % self.configure.rowNumber));
            make.top.mas_equalTo(self.configure.verticalClearance + (self.configure.itemSize.height + self.configure.verticalClearance)*(index / self.configure.rowNumber));
            make.width.mas_equalTo(self.configure.itemSize.width);
            make.height.mas_equalTo(self.configure.itemSize.height);
        }];
        
    }
    
    self.choosePhotosArrayM = [NSMutableArray array];
    
    self.chooseAssetsArrayM = [NSMutableArray array];
    
}
    //MARK: - 单个删除选取的某张图片
-(void)deleteCurrentImageClick:(UIButton *)sender{
    
    [self.choosePhotosArrayM removeObjectAtIndex:sender.superview.tag];
    [self.chooseAssetsArrayM removeObjectAtIndex:sender.superview.tag];
    
    [self reloadData];
    
   
    if (self.configure.isVideo) {
        if(self.choosePhotosViewDidFinishPickingVideosHandle){
            self.choosePhotosViewDidFinishPickingVideosHandle(self.choosePhotosArrayM, self.chooseAssetsArrayM);
        }
    }else{
        if (self.choosePhotosViewDidFinishPickingPhotosHandle) {
            self.choosePhotosViewDidFinishPickingPhotosHandle(self.choosePhotosArrayM);
        }
    }
}
    //MARK: - 点击选取新照片
-(void)choosedPhotosClick:(UIButton *)sender{
    
    if (self.jp_willPresentImagePickerControllerBlock() == false) {
        
        return;
    }
 
 
    if (sender.superview.tag == self.choosePhotosArrayM.count ) {
        
        TZImagePickerController * picker = [[TZImagePickerController alloc] initWithMaxImagesCount:self.configure.maxNum delegate:nil];
        
        //设置是否可以选择视频/图片/原图
        picker.selectedAssets = self.chooseAssetsArrayM;
        
        picker.sortAscendingByModificationDate = false;
        
        picker.allowPickingVideo = self.configure.isVideo;
        
        picker.allowPickingImage = !self.configure.isVideo;
        
        picker.allowTakePicture = true;
        
        picker.allowPickingOriginalPhoto = true;
                
        [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:picker animated:true completion:nil];
        
        __weak typeof(self)weakself = self;
        
        picker.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            
            __strong typeof(weakself)strongself = weakself;
            
            strongself.chooseAssetsArrayM = [NSMutableArray arrayWithArray:assets];
            
            strongself.choosePhotosArrayM = [NSMutableArray arrayWithArray:photos];
            
            if (strongself.choosePhotosViewDidFinishPickingPhotosHandle) {
                strongself.choosePhotosViewDidFinishPickingPhotosHandle(photos);
            }
            
        };
        
        
        picker.didFinishPickingVideoHandle = ^(UIImage *coverImage, PHAsset *asset) {
          
            __strong typeof(weakself)strongself = weakself;
            
            strongself.chooseAssetsArrayM = [NSMutableArray arrayWithArray:@[asset]];
            
            strongself.choosePhotosArrayM = [NSMutableArray arrayWithArray:@[coverImage]];
            
            if (strongself.choosePhotosViewDidFinishPickingVideosHandle) {
                strongself.choosePhotosViewDidFinishPickingVideosHandle(self.choosePhotosArrayM, self.chooseAssetsArrayM);
            }
            
        };
        
    }
    
}
    //MARK: - 更新按钮状态
-(void)reloadData{
    
    //当前未选取图片
    if (self.choosePhotosArrayM.count == 0){
        
        [self.buttonsArrayM enumerateObjectsUsingBlock:^(JPPhotoView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (idx == 0) {
                obj.hidden = false;
                obj.deleteBtn.hidden = true;
                [obj.photoBtn setBackgroundImage:self.configure.addphotoImage forState:UIControlStateNormal];
                
            }else{
                obj.hidden = true;
            }
        }];
        
    }else if (self.configure.maxNum == self.choosePhotosArrayM.count) {
    //选取图片达到设定最大数量
        
        [self.buttonsArrayM enumerateObjectsUsingBlock:^(JPPhotoView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            
            obj.hidden = true;
            
            if (idx < self.configure.maxNum) {
                
                obj.hidden = false;
                obj.deleteBtn.hidden = false;
                [obj.photoBtn setBackgroundImage:self.choosePhotosArrayM[idx] forState:UIControlStateNormal];
                
            }
            
        }];
        
        //有选取的图片，但未达到最大值（可追加选取图片）
    } else {
        
        [self.buttonsArrayM enumerateObjectsUsingBlock:^(JPPhotoView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (idx < self.choosePhotosArrayM.count) {
                
                obj.hidden = false;
                obj.deleteBtn.hidden = false;
                [obj.photoBtn setBackgroundImage:self.choosePhotosArrayM[idx] forState:UIControlStateNormal];
                
            }else if (idx == self.choosePhotosArrayM.count){
                
                obj.hidden = false;
                obj.deleteBtn.hidden = true;
                [obj.photoBtn setBackgroundImage:self.configure.addphotoImage forState:UIControlStateNormal];
                
            }else{
                obj.hidden = true;
                obj.deleteBtn.hidden = true;
                obj.hidden = true;
                
            }
            
        }];
        
    }
    
    //视频按钮
    [self.buttonsArrayM enumerateObjectsUsingBlock:^(JPPhotoView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        obj.videoButton.layer.cornerRadius = self.configure.imageCornerRadius;
        
        [obj.videoButton setImage:self.configure.videoImage forState:UIControlStateNormal];

        obj.videoButton.hidden = !(self.configure.isVideo && self.chooseAssetsArrayM.count > 0);
        
        if (self.configure.deleteType == JPPhotoDeleteTypeDefalts) {
            [obj.deleteBtn mas_updateConstraints:^(MASConstraintMaker *make) {
//                make.top.mas_equalTo(-10);
//                make.right.mas_equalTo(10);
                make.top.mas_equalTo(obj.photoBtn.mas_top).offset(-10);
                make.right.mas_equalTo(obj.photoBtn.mas_right).offset(10);
//                make.width.height.mas_equalTo(20);
            }];
        }else{
            [obj.deleteBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(obj.photoBtn.mas_top).offset(0);
                make.right.mas_equalTo(obj.photoBtn.mas_right).offset(0);
//                make.width.height.mas_equalTo(20);
            }];
        }
        
        
    }];
    
    
    //每次重新排版时更新按钮父视图大小
    [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
        make.size.mas_equalTo([self jp_estimatedSize]);
    }];
    
    [self layoutIfNeeded];

    
}
    //MARK: - 计算content高度
-(CGSize)jp_estimatedSize{
    
    NSInteger choosedNum = self.choosePhotosArrayM.count > 0 ? self.choosePhotosArrayM.count : 1;
 
    CGFloat kViewActualHeight = 0;
    
    if (choosedNum == self.configure.maxNum) {
        
        CGFloat  tmpColumn = self.configure.maxNum  / self.configure.rowNumber;
        CGFloat  tmpRedundant = self.configure.maxNum * 1.0 / self.configure.rowNumber - tmpColumn;
        if (tmpRedundant > 0) {//判断当前排列方式下最后一行是否有多余
            tmpColumn += 1;//有多余则需要多添加一行
        }
        
        kViewActualHeight = (self.configure.itemSize.height + self.configure.horizontalClearance) * tmpColumn + self.configure.horizontalClearance;
        
    }else{
        
        CGFloat  tmpColumn = (choosedNum + 1)  / self.configure.rowNumber;
        CGFloat  tmpRedundant = (choosedNum + 1.0)  / self.configure.rowNumber - tmpColumn;
        if (tmpRedundant > 0) {//判断当前排列方式下最后一行是否有多余
            tmpColumn += 1;//有多余则需要多添加一行
        }
        
        kViewActualHeight = (self.configure.itemSize.height + self.configure.horizontalClearance) * tmpColumn + self.configure.horizontalClearance;
        
    }
    
    
    return CGSizeMake(self.configure.viewWidth, kViewActualHeight);
    
}

@end


